const crawler = require('../webCrawler/china')
// const model = require('../mongoseDb/model')
// const filmType = model.getModel('film_type')
// const Film = model.getModel('film')
const pageQuery = require('../utils/pageQuery')
const PagingUtil = require('../utils/sqlPage')
const AsyncMysqljs = require('../mysql/index')
const Query = AsyncMysqljs().query
const Get = AsyncMysqljs().get


  



const fs = require('fs')
var fn_index = async(ctx, next) => {
    const {page, pageSize, type} = ctx.request.query
    const sql = 'SELECT * FROM film_type'
    const typeList = await Query(sql)
    
    var init_page= page || 1;//默认页码为1
    var num = 20;//每页要显示的数据量
    
    var start = 0;//设置起始数据为第一条
    if(init_page>1){
        start = (init_page-1) * num; //页码减去1，乘以条数就得到分页的起始数了
    }
    let filmListSql = ''
    let filmList = []
    let pageCount = 0
    const codeParams = 'id, pic_url, name'
    if(type) {
        filmListSql = `SELECT ${codeParams} FROM film WHERE type=? AND is_show=? ORDER BY create_time DESC limit ${start},${num}`
        filmList = await Query(filmListSql,[type, 1])
        pageCount = await Query('SELECT COUNT(*) FROM film WHERE type=? AND is_show=?', [type, 1])
    } else {
        filmListSql = `SELECT ${codeParams} FROM film WHERE is_show=? ORDER BY create_time DESC limit ${start},${num}`
        pageCount = await Query('SELECT COUNT(*) FROM film')
        filmList = await Query(filmListSql, [1])
    }
    
    ctx.render('index.html', {
        filmType: typeList,
        filmList: filmList,
        page: init_page,
        pageSize: pageSize,
        pageCount: Math.ceil(pageCount[0]['COUNT(*)'] / num),
        total: pageCount[0]['COUNT(*)']
    });
};

var fn_signin = async(ctx, next) => {
    var name = ctx.request.body.name || '',
        password = ctx.request.body.password || '';
    if (name === 'koa' && password === '12345') {
        ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
    } else {
        ctx.response.body = `<h1>Login failed!</h1>
        <p><a href="/">Try again</a></p>`;
    }
};

const initFilmType = async(ctx, next) => {
    filmType.create({
        name: '其他电影',
        value: 3
    }, function(err, doc){
        if(err) console.log(err)
    })
    ctx.response.body = 'ok'
}
const getFilm = async(ctx, next) => {
    const {value} = ctx.request.query 
    if(!value) {
        ctx.response.body = '没有传value值！'
        return
    }
    const arr = await crawler(value)
    for(let i = 0; i < arr.length; i++ ) {
        let item = arr[i]
        const sql = 'INSERT INTO film(type, is_show, name, pic_url, down_url, desc_txt, thunder_url, down_type) VALUES(?, ?, ?, ?, ?, ?, ?, ?)'
        const film = await Query(sql, [value, 1, item.movieName, item.pic, item.downLink, item.desc, item.thunder_url, 0])
    }
    ctx.response.body = '成功！'
}

const filDetail = async(ctx, next) => {
    const {id} = ctx.request.query
    const sql = 'SELECT * FROM film_type'
    const typeList = await Query(sql)
    const film = await Get('SELECT * FROM film WHERE id=?', [id])
    console.log(film)
    ctx.render('detail.html', {
        filmType: typeList,
        film: film
    });
}
const adminIndex = async (ctx, next) => {
    ctx.redirect('/dist/index.html');
    // ctx.type = 'html';
    // ctx.body = fs.readFileSync('../static/dist/index.html', 'utf8');
}

// 实现模糊查询
const searchFilm = async (ctx, next) => {
    const {name} = ctx.request.query
    const codeParams = 'id, pic_url, name'
    const sql = `SELECT ${codeParams} FROM film WHERE name like ?`
    try {
        const list = await Query(sql, [`%${name}%`])
        ctx.body = {
            code: 1,
            data: {
                list: list
            },
            msg: 'ok'
        }
    } catch(err) {
        ctx.body = {
            code: 0,
            data: {
                list: []
            },
            msg: err
        }
    }
}

 
const getCurrentDate = () => {
    const nowDate = new Date();
    const year = nowDate.getFullYear();
    const month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
    const day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
    const hour = nowDate.getHours();
    const minutes = nowDate.getMinutes();
    const seconds = nowDate.getSeconds();
    return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds;
}

const putInfo = async (ctx, next) => {
    const {name, phone, address} = ctx.request.body
    if(!phone){
        ctx.body = {
            code: 0,
            data: {},
            msg: '电话号码有误！'
        }
    }
    const create_date = getCurrentDate();
    
    const sql = 'INSERT INTO user_info(name, phone, address, create_date) VALUES(?, ?, ?, ?)'
    let info = {}
    try {
        info = await Query(sql, [name, phone, address, create_date])
        
    } catch {
        console.log('电话号码重复');
        
        ctx.body = {
            code: 2,
            data: {
            },
            msg: '电话号码重复！'
        }
    }
    ctx.body = {
        code: 1,
        data: {
            ...info
        },
        msg: 'ok'
    }
}

module.exports = {
    'GET /': fn_index,
    'POST /signin': fn_signin,
    'GET /getfilm': getFilm,
    'GET /detail': filDetail,
    'GET /admin': adminIndex,
    'GET /search': searchFilm,
    'POST /put/info': putInfo,
    // 'GET /initfilmtype': initFilmType
};